package com.mission.schedule.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mission.schedule.adapter.AddFriendsAdapter;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.AddFriendsBackBean;
import com.mission.schedule.bean.AddFriendsBean;
import com.mission.schedule.bean.SuccessOrFailBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.my160920.FrendBean;
import com.mission.schedule.my160920.adapter.FindFrendAdapter;
import com.mission.schedule.my160920.bean.FriendDownAllScheduleBean;
import com.mission.schedule.my160920.kankan.wheel.widget.WheelView;
import com.mission.schedule.my160920.picker.DatePicker;
import com.mission.schedule.my160920.picker.TimePicker;
import com.mission.schedule.utils.ActivityManager1;
import com.mission.schedule.utils.ListViewForScrollView;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.NetUtil.NetWorkState;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.PullToRefreshView;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mission.schedule.utils.Utils;
import com.mission.schedule.utils.PullToRefreshView.OnFooterRefreshListener;
import com.mission.schedule.utils.PullToRefreshView.OnHeaderRefreshListener;
import com.mission.schedule.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class FriendsSouSuoActivity extends BaseActivity implements
        OnClickListener, OnFooterRefreshListener, OnHeaderRefreshListener {

    @ViewResId(id = R.id.top_ll_left)
    private LinearLayout top_ll_left;
    @ViewResId(id = R.id.myfriend_pull_refresh_view)
    private PullToRefreshView mPullToRefreshView = null;
    @ViewResId(id = R.id.sousuojieguo_tv)
    private TextView sousuojieguo_tv;
    @ViewResId(id = R.id.nosousuojieguo_tv)
    private TextView nosousuojieguo_tv;
    @ViewResId(id = R.id.addfriends_lv)
    private ListViewForScrollView addfriends_lv;
    @ViewResId(id = R.id.sousuocontent_et)
    private EditText sousuocontent_et;
    @ViewResId(id = R.id.sousuo_iv)
    private ImageView sousuo_iv;
    @ViewResId(id = R.id.view)
    private View view;

    Context context;
    private boolean mRefreshHeadFlag = true;// 判断是否刷新的是头部
    private boolean mRefreshFlag = false;// 判断是否刷新
    private boolean isDel = true;
    AddFriendsAdapter addFriendsAdapter;
    List<AddFriendsBean> addFriendsList;

    String path;
    String SouSuoPath;

    SharedPrefUtil prefUtil = null;
    String userId;
    String type;
    int position;
    ActivityManager1 activityManager = null;

    //新增
    private boolean addb = false;

    private int isFriend = 0;
    private String cpidhandler = "";

    @Override
    protected void setListener() {
        top_ll_left.setOnClickListener(this);
        sousuo_iv.setOnClickListener(this);
//        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_friendssousuo);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        context = this;
        activityManager = ActivityManager1.getInstance();
        activityManager.addActivities(this);
        prefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        userId = prefUtil.getString(context, ShareFile.USERFILE,
                ShareFile.USERID, "");
        view.setVisibility(View.GONE);
        sousuojieguo_tv.setVisibility(View.VISIBLE);
        sousuojieguo_tv.setTextColor(Color.parseColor("#00000000"));

        //小蜜数量
        getFindCustomer();
    }

    @Override
    protected void setAdapter() {

    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            AddFriendsBean friendsbean = (AddFriendsBean) msg.obj;
            position = msg.arg1;
            switch (msg.what) {
                case 0:
                    String addPath = URLConstants.添加好友申请;
                    Map<String, String> addPairs = new HashMap<String, String>();
                    addPairs.put("uId", userId);
                    addPairs.put("fId", friendsbean.uid + "");
                    addPairs.put("uName", prefUtil.getString(context,
                            ShareFile.USERFILE, ShareFile.USERNAME, ""));

                    // + "?uId="
                    // + Integer.parseInt(userId)
                    // + "&fId="
                    // + friendsbean.uid
                    // + "&uName="
                    // + prefUtil.getString(context, ShareFile.USERFILE,
                    // ShareFile.USERNAME, "");
                    if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                        if (addFriendsList.get(msg.arg1).getIsFrends() == 0) {
                            isFriend = 0;
                        } else {
                            isFriend = 1;
                        }
                        addPersonCalender(addPairs, msg.arg1);
                    } else {
                        Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 1:
                    // int state;
                    // if (!"".equals(friendsbean.attentionState)
                    // && friendsbean.attentionState != null) {
                    // state = Integer.parseInt(friendsbean.attentionState);
                    // } else {
                    // state = 0;
                    // }
                    // Intent intent = new Intent(context,
                    // FriendsCRYActivity.class);
                    // intent.putExtra("fid", friendsbean.uid);
                    // intent.putExtra("name", friendsbean.uname);
                    // intent.putExtra("friendsimage", friendsbean.titleImg);
                    // intent.putExtra("friendsbackimage", friendsbean.backImage);
                    // intent.putExtra("attentionState", state);
                    // startActivity(intent);
                    break;

            }
        }

    };

    private void initdata() {
        if (Utils.checkMobilePhone(sousuocontent_et.getText().toString())) {
            type = "1";
        } else if (Utils.isEmail(sousuocontent_et.getText().toString())) {
            type = "2";
        } else {
            type = "0";
        }
        String uname = sousuocontent_et.getText().toString().trim();
        SouSuoPath = URLConstants.搜索添加好友;
        Map<String, String> pairs = new HashMap<String, String>();
        pairs.put("uId", userId);
        pairs.put("uName", uname);
        pairs.put("nowPage", "1");
        pairs.put("pageNum", "40");
        pairs.put("type", type);
        if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
            SouSuoAsync(SouSuoPath, pairs);
        } else {
            Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.top_ll_left:
                Intent intent = new Intent();
                intent.putExtra("cpidhandler",cpidhandler);
                setResult(Activity.RESULT_OK, intent);
                this.finish();
                break;
            case R.id.sousuo_iv:
                initdata();
                break;
            default:
                break;
        }
    }

    int i = 1;

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshHeadFlag = true;
                mRefreshFlag = true;
                i = 1;// 刷新头部时将页数初始化为1
                initdata();
                // mPullToRefreshView.onHeaderRefreshComplete();
            }
        }, 100);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        mPullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshHeadFlag = false;
                mRefreshFlag = true;
                ++i;
                Map<String, String> pairs = new HashMap<String, String>();
                pairs.put("uId", userId);
                pairs.put("uName", sousuocontent_et.getText().toString().trim());
                pairs.put("nowPage", i + "");
                pairs.put("pageNum", "40");
                pairs.put("type", type);
                String URLpath = URLConstants.搜索添加好友;
                SouSuoAsync(URLpath, pairs);
            }
        }, 100);
    }

    private void SouSuoAsync(String path, final Map<String, String> map) {
        final ProgressUtil progressUtil = new ProgressUtil();
        if (!mRefreshFlag) {
            progressUtil.ShowProgress(context, true, true, "正在努力加载......");
        }
        StringRequest request = new StringRequest(Method.POST, path,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {
                        if (mRefreshFlag) {
                            mPullToRefreshView.onHeaderRefreshComplete();
                            mPullToRefreshView.onFooterRefreshComplete();
                        } else {
                            progressUtil.dismiss();
                        }
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                if (mRefreshHeadFlag) {
                                    addFriendsAdapter = null;
                                }
                                Gson gson = new Gson();
                                AddFriendsBackBean backBean = gson.fromJson(
                                        result, AddFriendsBackBean.class);
                                if (backBean.status == 0) {
                                    if (addFriendsAdapter == null) {
                                        addFriendsList = backBean.list;
                                        if (addFriendsList != null
                                                && addFriendsList.size() > 0) {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv.setTextColor(context.getResources().getColor(R.color.gongkai_txt));
                                            view.setVisibility(View.VISIBLE);
                                        } else {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            view.setVisibility(View.GONE);
                                        }
                                        addFriendsAdapter = new AddFriendsAdapter(
                                                context, addFriendsList,
                                                R.layout.adapter_addfriends,
                                                handler);
                                        addfriends_lv
                                                .setAdapter(addFriendsAdapter);
                                    } else {
                                        addFriendsList.addAll(backBean.list);
                                        if (addFriendsList != null
                                                && addFriendsList.size() > 0) {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv.setTextColor(context.getResources().getColor(R.color.gongkai_txt));
                                            view.setVisibility(View.VISIBLE);
                                        } else {
                                            nosousuojieguo_tv
                                                    .setVisibility(View.VISIBLE);
                                            sousuojieguo_tv
                                                    .setVisibility(View.GONE);
                                            view.setVisibility(View.GONE);
                                        }
                                        addFriendsAdapter
                                                .notifyDataSetChanged();
                                    }
                                } else {
                                    return;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        } else {
                            if (isDel) {
                                addFriendsList = new ArrayList<AddFriendsBean>();
                                addFriendsAdapter = new AddFriendsAdapter(
                                        context, addFriendsList,
                                        R.layout.adapter_addfriends, handler);
                                addfriends_lv.setAdapter(addFriendsAdapter);
                            }
                            return;
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDel = false;
                progressUtil.dismiss();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    private void AddFriendsAsync(final Map<String, String> map, final int positions,final String content,final String time) {
        final ProgressUtil progressUtil = new ProgressUtil();
//        progressUtil.ShowProgress(context, true, true, "正在添加...");
        StringRequest request = new StringRequest(Method.POST, URLConstants.添加好友申请,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String result) {
//                        progressUtil.dismiss();
                        if (!TextUtils.isEmpty(result)) {
                            Gson gson = new Gson();
                            SuccessOrFailBean bean = gson.fromJson(result,
                                    SuccessOrFailBean.class);
                            if (bean.status == 0) {
                                AddFriendsBean friendsBean = (AddFriendsBean) addfriends_lv
                                        .getAdapter().getItem(position);
                                friendsBean.flag = false;
                                addFriendsAdapter.notifyDataSetChanged();
                                postPersonCalerder(position, addFriendsList.get(positions).getUid() + "", content, time);
                            } else {
                                Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                progressUtil.dismiss();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return map;
            }
        };
        request.setTag("down");
        request.setRetryPolicy(new DefaultRetryPolicy(10000, 1, 1.0f));
        App.getHttpQueues().add(request);
    }

    private void alertDialog() {
        final AlertDialog builder = new AlertDialog.Builder(context).create();
        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);// 设置生效
        window.setGravity(Gravity.CENTER);
        window.setContentView(R.layout.dialog_alert_ok);
        TextView delete_ok = (TextView) window.findViewById(R.id.delete_ok);
        delete_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                builder.cancel();
            }
        });

    }


    Dialog dialogs = null;
    private int cpost = 1;
    private int displayAlarm = 0;

    /**
     * 添加用户日程dialog
     *
     * @param position
     */
    private void addPersonCalender(final Map<String, String> map, int position) {
        Dialog dialog = new Dialog(context, R.style.dialog_translucent);
        Window window = dialog.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
        window.setAttributes(params);// 设置生效

        LayoutInflater fac = LayoutInflater.from(context);
        View more_pop_menu = fac.inflate(R.layout.dialog_add_person_calender, null);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setContentView(more_pop_menu);
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.width = ViewGroup.LayoutParams.MATCH_PARENT;

        new alterAddDialogOnClick(dialog, more_pop_menu, position, map);
    }

    /**
     * 添加用户日程dialog,点击事件
     */
    class alterAddDialogOnClick implements OnClickListener {

        private View view;
        private Dialog dialog;
        private TextView name, time, cancel, ok;
        private TextView zt, db;
        Button wancheng;
        private EditText content;
        private LinearLayout pickter_ll;

        private DatePicker dp_test;
        private TimePicker tp_test;

        final int position;
        private String selectDate, selectTime;
        private boolean contenttype = false;

        private final Map<String, String> map;

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        final Date date = new Date(System.currentTimeMillis());

        @SuppressLint("NewApi")
        public alterAddDialogOnClick(Dialog dialog, View view, int position, final Map<String, String> map) {
            this.dialog = dialog;
            this.view = view;
            this.position = position;
            this.map = map;
            initview();
            //滚动组布局

            dialog.show();
        }


        private void initview() {

            selectDate = simpleDateFormat.format(date).substring(0, 10);
            selectTime = simpleDateFormat.format(date).substring(11, 16);
            name = (TextView) view.findViewById(R.id.name);
            zt = (TextView) view.findViewById(R.id.zt);
            wancheng = (Button) view.findViewById(R.id.wancheng);
            content = (EditText) view.findViewById(R.id.content);
            content.setImeOptions(EditorInfo.IME_ACTION_SEND);
            time = (TextView) view.findViewById(R.id.time);
            pickter_ll = (LinearLayout) view.findViewById(R.id.pickter_ll);
            cancel = (TextView) view.findViewById(R.id.cancel);
            ok = (TextView) view.findViewById(R.id.ok);
            db = (TextView) view.findViewById(R.id.db);
            dp_test = (DatePicker) view.findViewById(R.id.dp_test);
            tp_test = (TimePicker) view.findViewById(R.id.tp_test);

            //设置滑动改变监听器
            dp_test.setOnChangeListener(dp_onchanghelistener);
            tp_test.setOnChangeListener(tp_onchanghelistener);

            name.setText("@" + addFriendsList.get(position).getUname());

            time.setText(simpleDateFormat.format(date));
            content.setFocusable(true);


            //打开软键盘
            imm.showSoftInput(content, 0);
            content.setOnClickListener(this);
            cancel.setOnClickListener(this);
            ok.setOnClickListener(this);
            zt.setOnClickListener(this);
            time.setOnClickListener(this);
            wancheng.setOnClickListener(this);
            db.setOnClickListener(this);
            /** 3.自动弹出软键盘 **/
            dialog.setOnShowListener(new DialogInterface.OnShowListener() {
                public void onShow(DialogInterface dialog) {
                    pickter_ll.setVisibility(View.GONE);
                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(content, InputMethodManager.SHOW_IMPLICIT);
                }
            });
        }


        //listeners
        DatePicker.OnChangeListener dp_onchanghelistener = new DatePicker.OnChangeListener() {
            @Override
            public void onChange(int year, int month, int day, int day_of_week) {
                selectDate = year + "-" + ((month < 10) ? "0" + month : month) + "-" + ((day < 10) ? "0" + day : day);
                time.setText(selectDate + " " + selectTime);
            }
        };
        TimePicker.OnChangeListener tp_onchanghelistener = new TimePicker.OnChangeListener() {
            @Override
            public void onChange(int hour, int minute) {
                selectTime = ((hour < 10) ? ("0" + hour) : hour) + ":" + ((minute < 10) ? ("0" + minute) : minute);
                time.setText(selectDate + " " + selectTime);
            }
        };


        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                //TODO
                case R.id.wancheng:
                    if (NetUtil.getConnectState(context) != NetWorkState.NONE) {
                        if (isFriend == 0) {
                            if (!content.getText().toString().trim().equals("") || !TextUtils.isEmpty(content.getText().toString())) {
                                postPersonCalerder(position, addFriendsList.get(position).getUid() + "", content.getText().toString(), time.getText().toString() + ":00");
                            } else {
                                Toast.makeText(context, "日程内容不能为空!", Toast.LENGTH_SHORT).show();
                            }
                        }else {
                            AddFriendsAsync(map,position, content.getText().toString(), time.getText().toString() + ":00");
                        }
                    } else {
                        Toast.makeText(context, "请检查您的网络是否正常！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.ok:
                    time.setTextColor(Color.parseColor("#30a9a0"));
                    //打开软键盘
                    imm.showSoftInput(content, 0);
                    pickter_ll.setVisibility(View.GONE);
                    cpost = 0;
                    contenttype = true;
                    displayAlarm = 1;
                    db.setTextColor(context.getResources().getColor(R.color.gray));
                    break;
                case R.id.cancel:
                    dialog.dismiss();
                    break;
                case R.id.zt:
                    //粘贴
                    ClipboardManager myClipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData abc = myClipboard.getPrimaryClip();
                    if (abc != null) {
                        ClipData.Item item = abc.getItemAt(0);
                        content.setText(content.getText().toString() + "" + item.getText().toString());
                        //修改光标位置
                        content.setSelection(content.getText().toString().length());
                    }

                    break;
                case R.id.time:
                    db.setTextColor(Color.parseColor("#555555"));
                    time.setTextColor(Color.parseColor("#30a9a0"));
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘

                    pickter_ll.setVisibility(View.VISIBLE);
                    break;
                case R.id.content:
                    if (contenttype == false) {
                        cpost = 1;
                        displayAlarm = 0;
                    }

                    if (cpost == 1) {
                        time.setTextColor(Color.parseColor("#555555"));
                        db.setTextColor(Color.parseColor("#30a9a0"));
                    }
                    pickter_ll.setVisibility(View.GONE);
                    imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
                    break;
                case R.id.db:
                    contenttype = false;
                    cpost = 1;
                    pickter_ll.setVisibility(View.GONE);
                    db.setTextColor(Color.parseColor("#30a9a0"));
                    time.setTextColor(Color.parseColor("#555555"));
                    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(content, InputMethodManager.SHOW_IMPLICIT);
                    break;
            }
        }
    }


    private void postPersonCalerder(int position, String id, String message, String time) {

        SharedPrefUtil sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);

        PersonCalerder(0, String.valueOf(addFriendsList.get(position).getUid()), id,
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "0"),
                time,
                sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, ""),
                addFriendsList.get(position).uname,
                message,
                addFriendsList.get(position).titleImg
        );
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (dialogs != null) {
            if (dialogs.isShowing() == false) {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
            }
        }
    }
    final ProgressUtil progressUtil = new ProgressUtil();
    /**
     * 对好友日程进行操作
     *
     * @param type      操作类型  0 添加 1删除  2修改
     * @param cpid
     * @param calendaId
     * @param uid
     * @param time
     * @param name
     * @param nickname
     * @param message
     * @param uPortrait
     */
    private void PersonCalerder(final int type, final String cpid, final String calendaId, final String uid, final String time, final String name, final String nickname, final String message, final String uPortrait) {
        progressUtil.ShowProgress(context, true, true, "日程添加中...");
        final JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            //添加的json
            if (type == 0) {
                jsonObject.put("CAlarmsound", "g_220");
                jsonObject.put("CAlarmsoundDesc", "短提示音");
                jsonObject.put("CLightAppId", 0);
                jsonObject.put("COpenstate", 0);
                jsonObject.put("CPostpone", cpost);
                jsonObject.put("CRecommendName", name);
                jsonObject.put("CTags", "");
                jsonObject.put("CType", 0);
                jsonObject.put("CTypeDesc", "");
                jsonObject.put("CTypeSpare", "");
                jsonObject.put("calendaId", 0);
                jsonObject.put("cbeforTime", 0);
                jsonObject.put("cdate", time.substring(0, 10));
                jsonObject.put("changTime", time);
                jsonObject.put("cisAlarm", 1);
                jsonObject.put("cpId", cpid);
                jsonObject.put("cretetime", time);
                jsonObject.put("ctime", time.substring(11, 16));

                jsonObject.put("atype", 0);
                jsonObject.put("downNum", 0);
                jsonObject.put("downstate", 0);
                jsonObject.put("endNum", 0);
                jsonObject.put("endState", "0");
                jsonObject.put("id", Integer.valueOf(calendaId));
                jsonObject.put("imgPath", "");
                jsonObject.put("lyNum", 0);
                jsonObject.put("message", message);
                jsonObject.put("parReamrk", "");
                jsonObject.put("pid", "");
                jsonObject.put("poststate", "0");
                jsonObject.put("remark", "");
                jsonObject.put("remark1", android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
                jsonObject.put("remark2", "");
                jsonObject.put("remark3", "");
                jsonObject.put("repCalendaState", 0);
                jsonObject.put("repCalendaTime", "");
                jsonObject.put("repColorType", 0);
                jsonObject.put("repDisplayTime", displayAlarm);
                jsonObject.put("repInStable", 1);
                jsonObject.put("repIsPuase", 0);
                jsonObject.put("repState", 0);
                jsonObject.put("repType", 0);
                jsonObject.put("repTypeParameter", "");
                jsonObject.put("repdatetwo", "");
                jsonObject.put("repinitialcreatedtime", "");
                jsonObject.put("replastcreatedtime", "");
                jsonObject.put("repnextcreatedtime", "");
                jsonObject.put("repstartdate", "");

                jsonObject.put("repstatetwo", 0);
                jsonObject.put("schIsImportant", 0);
                jsonObject.put("status", 1);
                jsonObject.put("uid", Integer.valueOf(uid));
                jsonObject.put("webUrl", "");
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonArray.put(jsonObject);

        Log.e("TAG", jsonArray.toString());

        StringRequest stringRequest = new StringRequest(Method.POST,URLConstants.HOST+"/appFrends_synFrendCalendaNew.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                Log.e("TAG", result);
                                PersonCalerder personCalerder = gson.fromJson(result, PersonCalerder.class);
                                if (personCalerder.status == 0) {
                                    List<PersonCalerderListBean> personCalerderListBeanList = personCalerder.list;
                                    if (personCalerderListBeanList.get(0).getState() == 0) {
                                        if (type == 0) {
                                            cpidhandler = cpid;
                                            addItem(cpid, uid, time, personCalerderListBeanList.get(0).calendId + "", name, message, nickname, uPortrait);
                                        }
                                    } else {
                                        dialogs.dismiss();
                                        progressUtil.dismiss();
                                        Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                                    }
                                }else {
                                    dialogs.dismiss();
                                    progressUtil.dismiss();
                                    Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                                dialogs.dismiss();
                                progressUtil.dismiss();
                                Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("TAG", "error:" + volleyError.toString());
                dialogs.dismiss();
                progressUtil.dismiss();
                Toast.makeText(context, "请检查你的网络情况!", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                //添加
                if (type == 0) {
                    map.put("data", "{addData:" + jsonArray.toString() + ",updateData:[],deleData:[]}");
                }
                //删除
                if (type == 1) {
                    map.put("data", "{addData:[],updateData:[] ,deleData:" + jsonArray.toString() + "}");
                }
                //修改
                if (type == 2) {
                    map.put("data", "{addData:[],updateData:" + jsonArray.toString() + ",deleData:[]}");
                }
                return map;
            }
        };
        stringRequest.setTag("synFrendCalendaNew");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }

    /**
     * 添加日程
     *
     * @param cpid
     * @param uid
     * @param time
     * @param calendId
     * @param name
     * @param message
     * @param nickname
     * @param uPortrait
     */
    private void addItem(String cpid, String uid, String time, String calendId, String name, String message, String nickname, String uPortrait) {
        FriendDownAllScheduleBean friendDownAllScheduleBean = new FriendDownAllScheduleBean();

        friendDownAllScheduleBean.setCAlarmsound("g_220");
        friendDownAllScheduleBean.setCAlarmsoundDesc("短提示音");
        friendDownAllScheduleBean.setCLightAppId("0");
        friendDownAllScheduleBean.setCOpenstate("1");
        friendDownAllScheduleBean.setCPostpone(cpost+"");
        friendDownAllScheduleBean.setCRecommendName(name);
        friendDownAllScheduleBean.setCTags("");
        friendDownAllScheduleBean.setCType("0");
        friendDownAllScheduleBean.setCTypeDesc("");
        friendDownAllScheduleBean.setCTypeSpare("");
        friendDownAllScheduleBean.setCalendaId("0");
        friendDownAllScheduleBean.setCbeforTime("0");
        friendDownAllScheduleBean.setCdate(time.substring(0, 10));
        friendDownAllScheduleBean.setChangTime(time);
        friendDownAllScheduleBean.setCisAlarm("0");
        friendDownAllScheduleBean.setCpId(cpid);
        friendDownAllScheduleBean.setCretetime(time);
        friendDownAllScheduleBean.setCtime(time.substring(11, 16));

        friendDownAllScheduleBean.setAtype("0");

        friendDownAllScheduleBean.setDownNum("0");
        friendDownAllScheduleBean.setDownstate("0");

        friendDownAllScheduleBean.setEndNum("0");
        friendDownAllScheduleBean.setEndState("0");

        friendDownAllScheduleBean.setId(calendId);
        friendDownAllScheduleBean.setImgPath("");
        friendDownAllScheduleBean.setLyNum("0");
        friendDownAllScheduleBean.setMessage(message);

        friendDownAllScheduleBean.setParReamrk("");
        friendDownAllScheduleBean.setPoststate("0");
        friendDownAllScheduleBean.setPid("");

        friendDownAllScheduleBean.setRemark("");
        friendDownAllScheduleBean.setRemark1(android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL);
        friendDownAllScheduleBean.setRemark2("");
        friendDownAllScheduleBean.setRemark3("");
        friendDownAllScheduleBean.setRepCalendaState("0");
        friendDownAllScheduleBean.setRepCalendaTime("0");
        friendDownAllScheduleBean.setRepColorType("0");
        friendDownAllScheduleBean.setRepDisplayTime(displayAlarm+"");
        friendDownAllScheduleBean.setRepInStable("0");
        friendDownAllScheduleBean.setRepIsPuase("0");
        friendDownAllScheduleBean.setRepState("0");
        friendDownAllScheduleBean.setRepType("0");
        friendDownAllScheduleBean.setRepTypeParameter("");
        friendDownAllScheduleBean.setRepdatetwo("0");
        friendDownAllScheduleBean.setRepinitialcreatedtime("");
        friendDownAllScheduleBean.setReplastcreatedtime("");
        friendDownAllScheduleBean.setRepnextcreatedtime("");
        friendDownAllScheduleBean.setRepstartdate("");
        friendDownAllScheduleBean.setRepState("");

        friendDownAllScheduleBean.setSchIsImportant("0");
        friendDownAllScheduleBean.setStatus("1");

        friendDownAllScheduleBean.setUid(uid);
        friendDownAllScheduleBean.setWebUrl("");


        App.getDBcApplication().insertFriendSchedule(friendDownAllScheduleBean);

        if (dialogs != null) {
            dialogs.dismiss();
        }
        progressUtil.dismiss();

        Intent intent = new Intent();
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    private static boolean isExit = false;
    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//			exit();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

//	private void exit() {
//		if (!isExit) {
//			isExit = true;
//			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
//			// 利用handler延迟发送更改状态信息
//			mHandler.sendEmptyMessageDelayed(0, 3000);
//		} else {
//			activityManager.doAllActivityFinish();
//		}
//	}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.getHttpQueues().cancelAll("down");
    }


    /**
     * 修改,删除,新增返回
     */
    public class PersonCalerder {

        /**
         * list : [{"id":1114,"calendId":857,"state":0,"dataState":1,"downTime":"2016-09-22 16:37:00"}]
         * message : 成功
         * status : 0
         */

        public String message;
        public int status;
        /**
         * id : 1114
         * calendId : 857
         * state : 0
         * dataState : 1
         * downTime : 2016-09-22 16:37:00
         */

        public List<PersonCalerderListBean> list;

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getStatus() {
            return status;
        }

        public void setStatus(int status) {
            this.status = status;
        }

        public List<PersonCalerderListBean> getList() {
            return list;
        }

        public void setList(List<PersonCalerderListBean> list) {
            this.list = list;
        }


    }

    public class PersonCalerderListBean {
        public int id;
        public int calendId;
        public int state;
        public int dataState;
        public String downTime;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getCalendId() {
            return calendId;
        }

        public void setCalendId(int calendId) {
            this.calendId = calendId;
        }

        public int getState() {
            return state;
        }

        public void setState(int state) {
            this.state = state;
        }

        public int getDataState() {
            return dataState;
        }

        public void setDataState(int dataState) {
            this.dataState = dataState;
        }

        public String getDownTime() {
            return downTime;
        }

        public void setDownTime(String downTime) {
            this.downTime = downTime;
        }
    }

    /**
     * 小蜜数量
     */
    private void getFindCustomer() {
        StringRequest stringRequest = new StringRequest(Method.POST, URLConstants.HOST+"/appFrends_findCustomer.do",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        if (!TextUtils.isEmpty(result)) {
                            try {
                                Gson gson = new Gson();
                                com.tencent.mm.sdk.platformtools.Log.e("TAG", result);
                                AddFriendsBackBean findC = gson.fromJson(result, AddFriendsBackBean.class);
                                if (findC.status == 0) {
                                    addFriendsList = findC.list;
                                    if (addFriendsList.size() > 0) {
                                        addFriendsAdapter = new AddFriendsAdapter(
                                                context, addFriendsList,
                                                R.layout.adapter_addfriends, handler);
                                        addfriends_lv.setAdapter(addFriendsAdapter);
                                        addFriendsAdapter.notifyDataSetChanged();
                                    }

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                com.tencent.mm.sdk.platformtools.Log.d("TAG", "error:" + volleyError.toString());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("uId", userId);

                return map;
            }
        };
        stringRequest.setTag("findCustomer");
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
        App.queues.add(stringRequest);
    }
}
